package application.anno.impl;

import application.anno.SetMouseActionMode;
import application.init.EventInit;
import application.util.ReflectionsUtil;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.input.DragEvent;
import lombok.SneakyThrows;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

public class SetMouseActionModeImpl {

    @SneakyThrows
    public void setMouseActionMode(Object controller) {
        Class<?> clazz = controller.getClass();
        Set<Field> fields = ReflectionsUtil.getAnnotationByField(SetMouseActionMode.class);
        Field[] declaredFields = clazz.getDeclaredFields();
        List<Field> fieldList = Arrays.asList(declaredFields);
        fields.retainAll(fieldList);
        for (Field field : fields) {
            if (field.getType().isInstance(Node.class)) {
                field.setAccessible(true);
                Node node = (Node) field.get(controller);
                node.setOnDragOver(new EventHandler<DragEvent>() {
                    @Override
                    public void handle(DragEvent event) {
                        SetMouseActionMode declaredAnnotation = field.getDeclaredAnnotation(SetMouseActionMode.class);
                        if (declaredAnnotation == null){
                            throw new NullPointerException("Not found SetMouseActionMode annotation");
                        }
                        EventInit.setOnDragOver(declaredAnnotation.action(), event);
                    }
                });
            }
        }
    }
}
